<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>HookFixChat仅供参考</title>
    <link rel="stylesheet" href="styles.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.7.0/styles/default.min.css">
</head>
<body>
    <div class="container">
        
        <div class="chat-box">
                
            <div class="messages" id="messages">HookFix Chat</div>
            <div class="input-area">
                
                <input type="text" id="input" placeholder="输入消息..." autocomplete="off">
                <button id="sendBtn">
                    <span>发送</span>
                    <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor">
                        <path d="M22 2L11 13M22 2l-7 20-4-9-9-4 20-7z"/>
                    </svg>
                </button>
                <button id="stopBtn" style="display: none;">
                    <span>停止输出</span>
                </button>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.7.0/highlight.min.js"></script>
    <script>
        const API_BASE = 'http://localhost:3000/api';
        const messagesEl = document.getElementById('messages');
        const inputEl = document.getElementById('input');
        const sendBtn = document.getElementById('sendBtn');
        const stopBtn = document.getElementById('stopBtn');

        // Markdown配置
        marked.setOptions({
            highlight: (code, lang) => hljs.highlightAuto(code).value,
            breaks: true
        });

        // 添加消息
        function addMessage(content, isUser) {
            const message = document.createElement('div');
            message.className = `message ${isUser ? 'user' : 'bot'}`;
            
            message.innerHTML = `
                <div class="avatar">${isUser ? '😎' : '🤠'}</div>
                <div class="content">${marked.parse(content)}</div>
            `;

            messagesEl.appendChild(message);
            messagesEl.scrollTop = messagesEl.scrollHeight;
            hljs.highlightAll();
        }

        // 显示加载动画
        function showLoadingAnimation() {
            const loadingMessage = document.createElement('div');
            loadingMessage.className = 'message bot';
            loadingMessage.innerHTML = `
               
                
            `;
            messagesEl.appendChild(loadingMessage);
            messagesEl.scrollTop = messagesEl.scrollHeight;
        }

        // 隐藏加载动画
        function hideLoadingAnimation() {
            const loadingMessage = messagesEl.querySelector('.message.bot');
            if (loadingMessage) {
                messagesEl.removeChild(loadingMessage);
            }
        }

        // 发送消息
        async function sendMessage() {
            const message = inputEl.value.trim();
            if (!message || sendBtn.disabled) return;

            sendBtn.disabled = true;
            stopBtn.style.display = 'inline-block';
            inputEl.value = '';
            addMessage(message, true);
            showLoadingAnimation();

            try {
                const response = await fetch(`${API_BASE}/chat`, {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ message })
                });

                const data = await response.json();
                if (!data.success) {
                    addMessage(`**发送失败**: ${data.error}`, false);
                }
            } catch (error) {
                addMessage(`**请求失败**: ${error.message}`, false);
            } finally {
                inputEl.focus();
            }
        }

        // 停止等待回复
        function stopWaiting() {
            hideLoadingAnimation();
            stopBtn.style.display = 'none';
            sendBtn.disabled = false;
        }

        // WebSocket 连接
        const ws = new WebSocket('ws://localhost:3001');
        ws.onmessage = (event) => {
            const message = JSON.parse(event.data);
            if (message.role === 'assistant') {
                hideLoadingAnimation();
                addMessage(message.content, false);
                stopBtn.style.display = 'none';
                sendBtn.disabled = false;
            }
        };

        // 初始化
        sendBtn.addEventListener('click', sendMessage);
        inputEl.addEventListener('keypress', e => e.key === 'Enter' && sendMessage());
        stopBtn.addEventListener('click', stopWaiting);

        // 加载历史记录
        fetch(`${API_BASE}/messages`)
            .then(res => res.json())
            .then(messages => messages.forEach(msg => 
                addMessage(msg.content, msg.role === 'user')
            ));
    </script>
</body>
</html>